namespace DotNetNuke.UI.UserControls
{
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Entities.Users;
    using DotNetNuke.Modules.HTMLEditorProvider;
    using DotNetNuke.Services.Exceptions;
    using DotNetNuke.Services.Localization;
    using DotNetNuke.Services.Personalization;
    using Microsoft.VisualBasic;
    using Microsoft.VisualBasic.CompilerServices;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Runtime.CompilerServices;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    /// -----------------------------------------------------------------------------
    /// Class:  TextEditor
    /// Project: DotNetNuke
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// TextEditor is a user control that provides a wrapper for the HtmlEditor providers
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// [cnurse]	12/13/2004	Documented
    /// </history>
    /// -----------------------------------------------------------------------------
    [ValidationProperty("Text")]
    public class TextEditor : UserControl
    {
        private static List<WeakReference> __ENCList = new List<WeakReference>();
        private bool _ChooseMode;
        private bool _ChooseRender;
        private Unit _Height;
        private bool _HtmlEncode;
        //("optRender")]
        private RadioButtonList _optRender;
        //("optView")]
        private RadioButtonList _optView;
        //("plcEditor")]
        private PlaceHolder _plcEditor;
        //("pnlBasicRender")]
        private Panel _pnlBasicRender;
        //("pnlBasicTextBox")]
        private Panel _pnlBasicTextBox;
        //("pnlOption")]
        private Panel _pnlOption;
        //("pnlRichTextBox")]
        private Panel _pnlRichTextBox;
        //("txtDesktopHTML")]
        private TextBox _txtDesktopHTML;
        private Unit _Width;
        private string MyFileName;
        private HtmlEditorProvider RichTextEditor;

        public TextEditor()
        {
            base.Init += new EventHandler(this.Page_Init);
            base.Load += new EventHandler(this.Page_Load);
            List<WeakReference> refObjectHelperL0 = __ENCList;
            lock (refObjectHelperL0)
            {
                __ENCList.Add(new WeakReference(this));
            }
            this._ChooseMode = true;
            this._ChooseRender = true;
            this._HtmlEncode = true;
            this.MyFileName = "TextEditor.ascx";
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Decodes the html
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="strHtml">Html to decode</param>
        /// <returns>The decoded html</returns>
        /// <history>
        /// [cnurse]	12/13/2004	Documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private string Decode(string strHtml)
        {
            if (this.HtmlEncode)
            {
                return this.Server.HtmlDecode(strHtml);
            }
            return strHtml;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Encodes the html
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="strHtml">Html to encode</param>
        /// <returns>The encoded html</returns>
        /// <history>
        /// [cnurse]	12/13/2004	Documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private string Encode(string strHtml)
        {
            if (this.HtmlEncode)
            {
                return this.Server.HtmlEncode(strHtml);
            }
            return strHtml;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Formats String as Html by replacing linefeeds by <br />
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="strText">Text to format</param>
        /// <returns>The formatted html</returns>
        /// <history>
        /// [cnurse]	12/13/2004	Documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private string FormatHtml(string strText)
        {
            string strHtml = strText;
            try
            {
                if (strHtml != "")
                {
                    strHtml = Strings.Replace(strHtml, "\r", "", 1, -1, CompareMethod.Binary);
                    strHtml = Strings.Replace(strHtml, "\n", "<br />", 1, -1, CompareMethod.Binary);
                }
            }
            catch (Exception exception1)
            {
                
                Exception exc = exception1;
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
                
            }
            return strHtml;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Formats Html as text by removing <br /> tags and replacing by linefeeds
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="strHtml">Html to format</param>
        /// <returns>The formatted text</returns>
        /// <history>
        /// [cnurse]	12/13/2004	Documented and modified to use HtmlUtils methods
        /// </history>
        /// -----------------------------------------------------------------------------
        private string FormatText(string strHtml)
        {
            string strText = strHtml;
            try
            {
                if (strText != "")
                {
                    strText = HtmlUtils.StripWhiteSpace(strText, true);
                    strText = HtmlUtils.FormatText(strText, false);
                }
            }
            catch (Exception exception1)
            {
                
                Exception exc = exception1;
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
                
            }
            return strText;
        }

        [DebuggerStepThrough]
        private void InitializeComponent()
        {
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// optRender_SelectedIndexChanged runs when Basic Text Box mode is changed
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	12/13/2004	Documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private void optRender_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.optRender.SelectedIndex != -1)
            {
                this.TextRenderMode = this.optRender.SelectedItem.Value;
            }
            if (this.Mode == "BASIC")
            {
                if (this.TextRenderMode == "H")
                {
                    this.txtDesktopHTML.Text = this.FormatHtml(this.txtDesktopHTML.Text);
                }
                else
                {
                    this.txtDesktopHTML.Text = this.FormatText(this.txtDesktopHTML.Text);
                }
            }
            this.SetPanels();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// optView_SelectedIndexChanged runs when Editor Mode is changed
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	12/13/2004	Documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private void optView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.optView.SelectedIndex != -1)
            {
                this.Mode = this.optView.SelectedItem.Value;
            }
            if (this.Mode == "BASIC")
            {
                if (this.TextRenderMode == "T")
                {
                    this.txtDesktopHTML.Text = this.FormatText(this.RichTextEditor.Text);
                }
                else
                {
                    this.txtDesktopHTML.Text = this.RichTextEditor.Text;
                }
            }
            else if (this.TextRenderMode == "T")
            {
                this.RichTextEditor.Text = this.FormatHtml(this.txtDesktopHTML.Text);
            }
            else
            {
                this.RichTextEditor.Text = this.txtDesktopHTML.Text;
            }
            this.SetPanels();
        }

        private void Page_Init(object sender, EventArgs e)
        {
            this.RichTextEditor = HtmlEditorProvider.Instance();
            this.RichTextEditor.ControlID = this.ID;
            this.RichTextEditor.Initialize();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	12/13/2004	Documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private void Page_Load(object sender, EventArgs e)
        {
            try
            {
                this.PopulateLists();
                UserInfo objUserInfo = UserController.GetCurrentUserInfo();
                this.RichTextEditor.Width = this.Width;
                this.RichTextEditor.Height = this.Height;
                this.txtDesktopHTML.Height = this.Height;
                this.txtDesktopHTML.Width = this.Width;
                if (!this.ChooseMode)
                {
                    this.pnlOption.Visible = false;
                }
                if (!this.ChooseRender)
                {
                    this.pnlBasicRender.Visible = false;
                }
                this.plcEditor.Controls.Add(this.RichTextEditor.HtmlEditorControl);
                this.SetPanels();
            }
            catch (Exception exception1)
            {
                
                Exception exc = exception1;
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
                
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Builds the radio button lists
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	12/13/2004	Documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private void PopulateLists()
        {
            if (this.optRender.Items.Count == 0)
            {
                this.optRender.Items.Add(new ListItem(DotNetNuke.Services.Localization.Localization.GetString("Text", DotNetNuke.Services.Localization.Localization.GetResourceFile(this, this.MyFileName)), "T"));
                this.optRender.Items.Add(new ListItem(DotNetNuke.Services.Localization.Localization.GetString("Html", DotNetNuke.Services.Localization.Localization.GetResourceFile(this, this.MyFileName)), "H"));
                this.optRender.Items.Add(new ListItem(DotNetNuke.Services.Localization.Localization.GetString("Raw", DotNetNuke.Services.Localization.Localization.GetResourceFile(this, this.MyFileName)), "R"));
            }
            if (this.optView.Items.Count == 0)
            {
                this.optView.Items.Add(new ListItem(DotNetNuke.Services.Localization.Localization.GetString("BasicTextBox", DotNetNuke.Services.Localization.Localization.GetResourceFile(this, this.MyFileName)), "BASIC"));
                this.optView.Items.Add(new ListItem(DotNetNuke.Services.Localization.Localization.GetString("RichTextBox", DotNetNuke.Services.Localization.Localization.GetResourceFile(this, this.MyFileName)), "RICH"));
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Sets the Mode displayed
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	01/10/2005	created (extracted from Page_load)
        /// </history>
        /// -----------------------------------------------------------------------------
        private void SetPanels()
        {
            if (this.optView.SelectedIndex != -1)
            {
                this.Mode = this.optView.SelectedItem.Value;
            }
            if (this.Mode != "")
            {
                this.optView.Items.FindByValue(this.Mode).Selected = true;
            }
            else
            {
                this.optView.SelectedIndex = 0;
            }
            if (this.optRender.SelectedIndex != -1)
            {
                this.TextRenderMode = this.optRender.SelectedItem.Value;
            }
            if (this.TextRenderMode != "")
            {
                this.optRender.Items.FindByValue(this.TextRenderMode).Selected = true;
            }
            else
            {
                this.optRender.SelectedIndex = 0;
            }
            if (this.optView.SelectedItem.Value == "BASIC")
            {
                this.pnlBasicTextBox.Visible = true;
                this.pnlRichTextBox.Visible = false;
            }
            else
            {
                this.pnlBasicTextBox.Visible = false;
                this.pnlRichTextBox.Visible = true;
            }
        }

        public bool ChooseMode
        {
            get
            {
                return this._ChooseMode;
            }
            set
            {
                this._ChooseMode = value;
            }
        }

        public bool ChooseRender
        {
            get
            {
                return this._ChooseRender;
            }
            set
            {
                this._ChooseRender = value;
            }
        }

        public string DefaultMode
        {
            get
            {
                if (Conversions.ToString(this.ViewState["DefaultMode"]) == "")
                {
                    return "RICH";
                }
                return Conversions.ToString(this.ViewState["DefaultMode"]);
            }
            set
            {
                if (value.ToUpper() != "BASIC")
                {
                    this.ViewState["DefaultMode"] = "RICH";
                }
                else
                {
                    this.ViewState["DefaultMode"] = "BASIC";
                }
            }
        }

        public Unit Height
        {
            get
            {
                return this._Height;
            }
            set
            {
                this._Height = value;
            }
        }

        public bool HtmlEncode
        {
            get
            {
                return this._HtmlEncode;
            }
            set
            {
                this._HtmlEncode = value;
            }
        }

        public string Mode
        {
            get
            {
                string strMode = "";
                if ((UserController.GetCurrentUserInfo().UserID >= 0) && (DotNetNuke.Services.Personalization.Personalization.GetProfile("DotNetNuke.TextEditor", "PreferredTextEditor") != null))
                {
                    strMode = Conversions.ToString(DotNetNuke.Services.Personalization.Personalization.GetProfile("DotNetNuke.TextEditor", "PreferredTextEditor"));
                }
                if (((strMode == null) | (strMode == "")) && (Conversions.ToString(this.ViewState["DesktopMode"]) != ""))
                {
                    strMode = Conversions.ToString(this.ViewState["DesktopMode"]);
                }
                if ((strMode == null) | (strMode == ""))
                {
                    strMode = this.DefaultMode;
                }
                return strMode;
            }
            set
            {
                UserInfo objUserInfo = UserController.GetCurrentUserInfo();
                if (value.ToUpper() != "BASIC")
                {
                    this.ViewState["DesktopMode"] = "RICH";
                    if (objUserInfo.UserID >= 0)
                    {
                        DotNetNuke.Services.Personalization.Personalization.SetProfile("DotNetNuke.TextEditor", "PreferredTextEditor", "RICH");
                    }
                }
                else
                {
                    this.ViewState["DesktopMode"] = "BASIC";
                    if (objUserInfo.UserID >= 0)
                    {
                        DotNetNuke.Services.Personalization.Personalization.SetProfile("DotNetNuke.TextEditor", "PreferredTextEditor", "BASIC");
                    }
                }
            }
        }

        protected virtual RadioButtonList optRender
        {
           
            get
            {
                return this._optRender;
            }
            
            set
            {
                EventHandler handler = new EventHandler(this.optRender_SelectedIndexChanged);
                if (this._optRender != null)
                {
                    this._optRender.SelectedIndexChanged -= handler;
                }
                this._optRender = value;
                if (this._optRender != null)
                {
                    this._optRender.SelectedIndexChanged += handler;
                }
            }
        }

        protected virtual RadioButtonList optView
        {
           
            get
            {
                return this._optView;
            }
            
            set
            {
                EventHandler handler = new EventHandler(this.optView_SelectedIndexChanged);
                if (this._optView != null)
                {
                    this._optView.SelectedIndexChanged -= handler;
                }
                this._optView = value;
                if (this._optView != null)
                {
                    this._optView.SelectedIndexChanged += handler;
                }
            }
        }

        protected virtual PlaceHolder plcEditor
        {
           
            get
            {
                return this._plcEditor;
            }
            
            set
            {
                this._plcEditor = value;
            }
        }

        protected virtual Panel pnlBasicRender
        {
           
            get
            {
                return this._pnlBasicRender;
            }
            
            set
            {
                this._pnlBasicRender = value;
            }
        }

        protected virtual Panel pnlBasicTextBox
        {
           
            get
            {
                return this._pnlBasicTextBox;
            }
            
            set
            {
                this._pnlBasicTextBox = value;
            }
        }

        protected virtual Panel pnlOption
        {
           
            get
            {
                return this._pnlOption;
            }
            
            set
            {
                this._pnlOption = value;
            }
        }

        protected virtual Panel pnlRichTextBox
        {
           
            get
            {
                return this._pnlRichTextBox;
            }
            
            set
            {
                this._pnlRichTextBox = value;
            }
        }

        public HtmlEditorProvider RichText
        {
            get
            {
                return this.RichTextEditor;
            }
        }

        public string Text
        {
            get
            {
                if (this.optView.SelectedItem.Value == "BASIC")
                {
                    switch (this.optRender.SelectedItem.Value)
                    {
                        case "T":
                            return this.Encode(this.FormatHtml(this.txtDesktopHTML.Text));

                        case "R":
                            return this.txtDesktopHTML.Text;
                    }
                    return this.Encode(this.txtDesktopHTML.Text);
                }
                return this.Encode(this.RichTextEditor.Text);
            }
            set
            {
                if (value != "")
                {
                    this.txtDesktopHTML.Text = this.Decode(this.FormatText(value));
                    this.RichTextEditor.Text = this.Decode(value);
                }
            }
        }

        public string TextRenderMode
        {
            get
            {
                return Conversions.ToString(this.ViewState["textrender"]);
            }
            set
            {
                string strMode = value.ToUpper().Substring(0, 1);
                if (((strMode != "R") & (strMode != "H")) & (strMode != "T"))
                {
                    strMode = "H";
                }
                this.ViewState["textrender"] = strMode;
            }
        }

        protected virtual TextBox txtDesktopHTML
        {
           
            get
            {
                return this._txtDesktopHTML;
            }
            
            set
            {
                this._txtDesktopHTML = value;
            }
        }

        public Unit Width
        {
            get
            {
                return this._Width;
            }
            set
            {
                this._Width = value;
            }
        }
    }
}

